package cn.jtfadmin.base.data.jpa.utils;

import cn.jtfadmin.base.lang.common.domain.dto.AntdvTreeDataRDTO;
import cn.jtfadmin.base.lang.common.domain.dto.TreeRDTO;
import cn.jtfadmin.base.lang.common.domain.entity.TreeEntity;

import java.util.*;
import java.util.stream.Collectors;

/**
 * tree 工具,将树实体转换为前端实体
 * @since 0.0.1
 * @author jtf
 */
public class TreeUtils {


    /**
     * 将treeEntity 转换为treeRDTO
     *
     * @param resultType 结果Class
     * @param source     元数据
     * @return treeRDTO 树型结构
     */
    public static <T extends TreeEntity, V> List<TreeRDTO<V>> buildTreeRDTO(Class<V> resultType, List<T> source) {
        return buildTreeRDTO(resultType, source, null);
    }

    /**
     * 将treeEntity 转换为treeRDTO
     *
     * @param resultType     结果Class
     * @param source         元数据
     * @param comparator     排序比较器 可null
     * @param ignoreProperty 复制时忽略的属性
     * @return treeRDTO 树型结构
     */
    public static <T extends TreeEntity, V> List<TreeRDTO<V>> buildTreeRDTO(Class<V> resultType, List<T> source, Comparator<T> comparator,
                                                      String... ignoreProperty) {
        return cn.jtfadmin.base.lang.common.utils.TreeUtils.buildTreeRDTO(resultType, source, "id", "parentId", comparator, ignoreProperty);
    }

    /**
     * 将tree entity转换为
     * @param source
     * @param comparator
     * @param showFields
     * @param <T>
     * @return
     */
    public static <T extends TreeEntity> List<AntdvTreeDataRDTO> buildAntdvTreeRDTO(List<T > source, Comparator<T> comparator, String... showFields){
        List<T> top = cn.jtfadmin.base.lang.common.utils.TreeUtils.findTopParent(source, "id", "parentId");
        Collections.sort(top, comparator);
        return top.stream().map(t->
                        cn.jtfadmin.base.lang.common.utils.TreeUtils.transferToAntdvTreeRDTO(t, source, "id", "parentId", comparator, showFields)
                ).collect(Collectors.toList());
    }

}
